package com.nav4fjnu.model;

import java.io.File;
import java.util.ArrayList;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseClient
{
	private SQLiteDatabase myDatabase = null;

	public SQLiteDatabase getMyDatabase()
	{
		return myDatabase;
	}

	public DatabaseClient()
	{
		String DATABASE_NAME = "site.db";
		String DATABASE_PATH = android.os.Environment
				.getExternalStorageDirectory().getAbsolutePath() + "/mydata";
		File filepath = new File(DATABASE_PATH);
		File dbpath = new File(DATABASE_PATH + "/" + DATABASE_NAME);
		if (!filepath.exists())
		{
			filepath.mkdirs();
		}
		if (!dbpath.exists())
		{
			try
			{
				dbpath.createNewFile();
			} catch (Exception e)
			{

			}
		}
		myDatabase = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH + "/"
				+ DATABASE_NAME, null);
	}

	public ArrayList<Site> search(String search_str)
	{
		ArrayList<Site> searchresult = new ArrayList<Site>();
		if (myDatabase.isOpen())
		{
			Cursor cursor = myDatabase.rawQuery(
					"select * from site where sitename like ?",
					new String[] { "%" + search_str + "%" });
			if (cursor.getCount() != 0)
			{
				for (cursor.moveToFirst(); !cursor.isLast(); cursor
						.moveToNext())
				{
					String siteno = cursor.getString(cursor
							.getColumnIndex("siteno"));
					String sitename = cursor.getString(cursor
							.getColumnIndex("sitename"));
					Double latitude = Double.parseDouble(cursor
							.getString(cursor.getColumnIndex("latitude")));
					Double longidute = Double.parseDouble(cursor
							.getString(cursor.getColumnIndex("longitude")));
					String detail = cursor.getString(cursor
							.getColumnIndex("detail"));
					searchresult.add(new Site(siteno, sitename, latitude,
							longidute, detail));
				}
			} else
			{
				return null;
			}
			cursor.close();
		}
		return searchresult;
	}
}
